package com.example.springboot.services.impl;

import com.example.springboot.domain.PageBean;
import com.example.springboot.domain.User;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.services.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    public PageBean<User> pageQuery(Integer page, Integer pageSize, String  username, String  name, String sex){
        PageBean<User> userPage=new PageBean<>();

        //获取用户数据
        List<User> lists = userMapper.searchUser(page,pageSize,username,name,sex);
        userPage.setData(lists);

        //获取数据总数
        Integer count=userMapper.searchUserCount(username,name,sex);
        userPage.setTotal(count);

        return userPage;
    }

    @Override
    public Boolean delUserById(Long id) {
        if(id!=null) {
            Integer count = userMapper.delUserById(id);
            if(count!=0) return true;
            log.warn("删除失败");
            return false;
        }
        return false;
    }

    @Override
    public Boolean addUser(User user) {

        //查找相同用户名
        String username=userMapper.findByUsername(user.getUsername());
        //存在相同用户名，返回相同信息
        if(user.getUsername().equals(username)){
            log.warn("存在同名用户");
            return false;
        }
        //添加用户
        Integer count=userMapper.insert(user);
        //判断结果是否为0,不为0则添加成功
        if(count!=0)   return true;;
        //否则返回失败信息
        return false;

    }

    @Override
    public Boolean updateUser(User user) {
        //查找是否存在用户
        User user2=userMapper.findUserById(user.getId());
        if(user2 == null) {
            return false;
        }
        //查找相同用户名
        String username=userMapper.findByUsername(user.getUsername());
        //存在相同用户名，返回相同信息
        if(user.getUsername().equals(username)){
            log.warn("存在同名用户");
            return false;
        }
        if ((userMapper.updateUser(user)) != 0) return true;
        return false;

    }

    @Override
    public User findUserById(Long id) {
        //查找是否存在用户
        User user=userMapper.selectById(id);
        return user;
    }

    @Override
    public List<User> findUserByIdList(List<Long> idList) {
        //获取用户数据
        List<User> users = userMapper.findUserByIdList(idList);
        return users;
    }
}
